/**
 *created by xuqiang 19/12/2
 */
'use strict';
import store from '../stores/module/webSocketStore'

let webSocketService = {};

webSocketService.backType = {
    handShake:'handShake'
};
webSocketService.initMessage = {
    type:webSocketService.backType.handShake,
    beizhu:'握手',
    content:'',
    wsURL:window.location.host //wsURL地址  根据实际自行修改  "ws://127.0.0.1:8080/web/web.ws"
};
webSocketService.getWstimeOut = false;
webSocketService.index = 0;
webSocketService.ws = '';
/**
 *初始化打开连接进行握手，不用等到发信息才握手
 * @param {object/string} msg  发送的信息
 */
webSocketService.initWebSocket = (msg)=>{
    let message = {};
    if(typeof msg=='string'){
        webSocketService.initMessage.content = msg;
        message = Object.assign({},webSocketService.initMessage);
    }else if(msg && Object.keys(msg).length>0){
        message = Object.assign({},webSocketService.initMessage,msg);
    }
    webSocketService.ws = webSocketService.newWebSocket(message.wsURL);
    webSocketService.sendMessage(message);
};
/**
 *建立WebSocket连接
 * @param {string}wsURL  地址
 * return WebSocket
 */
webSocketService.newWebSocket = (wsURL)=>{
    let wsUrl = wsURL;
    let wsTmp = '';
    console.log(`webSocketServiceUrl>>>>>>>>>>>>>>>${wsUrl}`);
    if('WebSocket' in window){
        wsTmp = new WebSocket(wsUrl); //实例化一个 WebSocket
    }else if('MozWebSocket' in window){
        wsTmp = new MozWebSocket(wsUrl); //实例化一个 MozWebSocket
    }else{
        console.error('不支持 WebSocket');
    }
    if(wsTmp){
        //建立连接成功后触发
        wsTmp.onopen = (evt)=>{
            webSocketService.onOpen(evt);
        };
        //响应意外故障时触发
        wsTmp.onerror = (evt)=>{
            webSocketService.onError(evt);
        };
        //关闭连接时触发
        wsTmp.onclose = (evt)=>{
            webSocketService.onClose(evt);
        };
        //有信息推送时触发
        wsTmp.onmessage = (evt)=>{
            webSocketService.onMessage(evt);
        };
    }
    return wsTmp;
};
/**
 *发送消息
 * @param {object} message 发送的信息
 * WebSocket.CONNECTING=0 连接正在进行中，但还未建立
 * WebSocket.OPEN=1 连接已建立，消息开始传递
 * WebSocket.CLOSING=2 连接正在进行关闭
 * WebSocket.CLOSED=3 连接已关闭
 */
webSocketService.sendMessage = (message)=>{
    if(message){
        if(sessionStorage.getItem('userInfo')){
            message.loginId = JSON.parse(sessionStorage.getItem('userInfo')).loginId;
        }
        if(webSocketService.ws && webSocketService.ws.readyState===WebSocket.OPEN){
            let msg = JSON.stringify(message);
            webSocketService.ws.send(msg);
        }else{
            webSocketService.getWstimeOut = true;
            webSocketService.sendAction(message)
        }
    }
};
/**
 *重新连接
 */
webSocketService.sendAction = (message)=>{
    if(webSocketService.getWstimeOut){
        setTimeout(()=>{
            if(!webSocketService.ws || webSocketService.ws.readyState===WebSocket.CLOSED){
                webSocketService.index++;
                console.log('正在建立连接，请稍等...'+webSocketService.index);
                if(webSocketService.index<20){
                    webSocketService.ws = webSocketService.newWebSocket(message.wsURL);
                }else{
                    console.log('连接建立失败，请刷新页面！！！');
                    webSocketService.getWstimeOut = false;
                }
            }else if(webSocketService.ws.readyState===WebSocket.OPEN){
                console.log('连接已建立，消息开始传递，请稍等...');
                let msg = JSON.stringify(message);
                webSocketService.ws.send(msg);
                webSocketService.getWstimeOut = false;
            }else if(webSocketService.ws.readyState===WebSocket.CONNECTING){
                console.log('连接正在进行中，但还未建立，请稍等...');
            }else if(webSocketService.ws.readyState===WebSocket.CLOSING){
                console.log('连接正在进行关闭，请稍等...')
            }
            webSocketService.sendAction(message);
        },500)
    }
};
webSocketService.onOpen = (evt)=>{console.log("socket连接成功");};
webSocketService.onError = (evt)=>{console.log(`启动连接失败，请刷新页面重试！错误码:${evt.description}`);};
webSocketService.onClose = (evt)=>{console.log(`socket连接关闭`);};
webSocketService.onMessage = (evt)=>{
    if(typeof evt.data ==='string'){
        let result = JSON.parse(evt.data);
        // console.log(result);
        store.commit('wsStore_upDataMsg',result)
    }
    if(evt.data instanceof Blob){
        //二进制数据
    }
};

export default webSocketService

/**
 *在 .vue 引入
 * import webSocketService from '@/utils/webSocketService.js'

 *也可在 main.js 全局引入
 *import webSocketService from './utils/webSocketService.js'
 *Vue.prototype.webSocketService = webSocketService;

 *在使用地方调用
 *[this.]webSocketService.initWebSocket('先握个手');

 *在需要使用服务端推送过来的消息时
 *在computed方法声明
 getWsMsg() {
   //在核心代码接收到的服务端信息存储到vuex的属性
    return this.$store.state.webSocketStore.wsStore_msg
 }
 getWsMsg1() {
   //在核心代码接收到的服务端信息存储到vuex的属性
    return this.$store.state.webSocketStore.wsStore_msg1
 }
 *在watch方法   监听  getWsMsg
 getWsMsg: function (data, val) {
   console.log(data);
   //.......
 }
 getWsMsg1: function (data, val) {
   console.log(data);
   //.......
 }

 *发送消息
 * webSocketService.sendMessage({'content':'要发送的消息'})

*关闭
 * webSocketService,可以在beforeRouteLeave里关闭
beforeRouteLeave(){
        if(webSocketService.ws) webSocketService.ws.close();
 }
*/




